using System;
using System.Data;
using System.Web.Mvc;
using ExampleWebApplication.Infraestruture.NHibernate;
using NHibernate;

namespace ExampleWebApplication.Filters
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class ApplyTransactionAttribute : ActionFilterAttribute
    {
        private ITransaction _currentTransaction;
        public bool ReadOnly { get; set; }

        public ApplyTransactionAttribute()
        {
            ReadOnly = true;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                _currentTransaction = NHibernateHelper.CurrentSession.Transaction;

                if (_currentTransaction.IsActive) return;

                if (ReadOnly)
                    _currentTransaction.Begin(IsolationLevel.ReadCommitted);
                else
                    _currentTransaction.Begin();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }


        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            try
            {
                if (!_currentTransaction.IsActive) return;

                if (filterContext.Exception == null && HasOpenTransaction())
                {
                    _currentTransaction.Commit();
                }
                else if (!_currentTransaction.WasRolledBack)
                {
                    _currentTransaction.Rollback();
                }
                _currentTransaction.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }

        public bool HasOpenTransaction()
        {
            return _currentTransaction != null && !_currentTransaction.WasCommitted && !_currentTransaction.WasRolledBack;
        }
    }
}